package com.century.sjt.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.allinpay.appayassistex.APPayAssistEx;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.EMChat.activity.ChatActivity;
import com.century.sjt.R;
import com.century.sjt.activity.Pay.PayPalWindowActivity;
import com.century.sjt.activity.setting.Setting_pwdPayActivity;
import com.century.sjt.adapter.ChoosePayAdapter;
import com.century.sjt.entity.BankCard;
import com.century.sjt.entity.Merchant;
import com.century.sjt.util.Constant;
import com.century.sjt.util.SrcUtil;
import com.century.sjt.util.TipUtil;
import com.century.sjt.utils.PreferenceManager;
import com.century.sjt.window.PayPopupWindow;
import com.century.sjt.window.SelectPicPopupWindow;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import com.century.sjt.activity.setting.Setting_pwdPayActivity;


/**
 * tab 商家支付
 */
public class MerchantItemPayFragment extends BaseFragment {


    private Context mContext;
    private Button btnPay;
    private TextView tvBalance;
    private TextView tvRebate;
    private TextView tvPayS;
    private EditText etAccountAmount,etAccountRebate;
    private String mAmount;//余额
    private String merchantId, balance,amount,aRebateAccount,Bamount,payType;
    private Double rebates=0.0,account=0.0,multiply=0.0,SettleAmount=0.0;
    private LinearLayout accountLayout,rebateLayout,payTypeLayout,Layout_addBankPay,tvBalanceLayout;
    private View view0,view1,view2,view3,view4;
    private ListView listView;
    //自定义的弹出框类
    SelectPicPopupWindow menuWindow;
    PayPopupWindow payWindow;
    private  String orderNo="";
    private  String cardNo="";
    private  BigDecimal bigDecimal;
    private  BigDecimal bigDecimal2;
    private BigDecimal bigDecimal3;
    private BigDecimal bigDecimalMultiply;
    private BigDecimal bigDecimalSettleAmount;

    private final BankCard payBack = new BankCard();
    private ChoosePayAdapter adapter;
    private RequestQueue mQueue;
    private List<BankCard> mDatalist;
    private Handler mHandler;
    private Merchant aMerchant;
    private String toPayType="0";
    private LinearLayout currencyrebateLayout;
    private TextView currencyrebate;
    private String isVIP="";
    private TextView icon_vip;
    private String MyRebate;
    private List<BankCard> mCardList = new ArrayList<>();
    private List<BankCard> mMTList = new ArrayList<>();
    private double mExRate;
    private TextView pay_type;
    private TextView pay_mtype;
    private TextView tv_exchange_rate;
    private LinearLayout layout_exchange_rate;
    private LinearLayout layout_exchange_mExRate;
    private TextView tv_amount_mExRate;
    private TextView tv_exchange_mExRate;
    private TextView currency_type;

    public String getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.sjt_merchant_pay_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext=getActivity();
        mQueue = Volley.newRequestQueue(getActivity());
        //读取id
        Intent intent = getActivity().getIntent();
        payType=intent.getStringExtra("payType");

        aMerchant=(Merchant)intent.getSerializableExtra("Merchant");
        initViews();
        countAmount(aMerchant);
//        shopDetail(aMerchant.getShopId());
    }

    private void initEvents(final String rebate,final String exRate) {

        rebates=Double.parseDouble(rebate);
        rebates=rebates/10;
        //实例化SelectPicPopupWindow
        MyRebate = rebate;
        mExRate = Double.parseDouble(exRate);
//        payTypeLayout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////
//                String tAmount = etAccountAmount.getText().toString();
//
//                if ("".equals(tAmount)||null==tAmount){
//                    TipUtil.showToast(getResources().getString(R.string.error_please_input_amount), getActivity(), 1);
//                }else {
//                    InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
//                    imm.hideSoftInputFromWindow(etAccountAmount.getWindowToken(),0);
//                    GetPayType("1",merchantId,tAmount);
//                }
//
//            }
//        });
        btnPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                BuyPay(rebate);

                String tAmount = etAccountAmount.getText().toString();

                if ("".equals(tAmount)||null==tAmount){
                    TipUtil.showToast(getResources().getString(R.string.error_please_input_amount), getActivity(), 1);
                }else {
                    InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(etAccountAmount.getWindowToken(),0);
                    GetPayType("1",merchantId,tAmount);
                }
            }
        });

        //软键盘设置
        etAccountAmount.setOnEditorActionListener(new TextView.OnEditorActionListener(){
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                 /*判断是否是“GO”键*/
                if(actionId == EditorInfo.IME_ACTION_NEXT){
                    /*隐藏软键盘*/
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
//                    if (imm.isActive()) {
//                        imm.hideSoftInputFromWindow(
//                                v.getApplicationWindowToken(), 0);
//                    }

//                    edittext.setText("success");
//                    webview.loadUrl(URL);
                    BuyPay(rebate);
                    return true;
                }
                return false;
            }
        });



        etAccountAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        etAccountAmount.setText(s);
                        etAccountAmount.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    etAccountAmount.setText(s);
                    etAccountAmount.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        etAccountAmount.setText(s.subSequence(0, 1));
                        etAccountAmount.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

                amount = etAccountAmount.getText().toString();
                if (amount.equals("") || amount == null) {
                    etAccountRebate.setText(" ");
                } else {

                    account = Double.parseDouble(etAccountAmount.getText().toString());
                    //注意需要使用BigDecimal(String val)构造方法
                    bigDecimal = new BigDecimal(Double.toString(account));//本金
                    bigDecimal2 = new BigDecimal(Double.toString(rebates));//折扣
                    bigDecimal3 = new BigDecimal(Double.toString(mExRate));//汇率
                    //乘法
                    bigDecimalMultiply = bigDecimal.multiply(bigDecimal2);
//                    Log.e("b1",account+"*"+rebates+"="+bigDecimalMultiply.toString());
                    bigDecimalSettleAmount = bigDecimalMultiply.multiply(bigDecimal3);
//                    Log.e("b2",bigDecimalMultiply.toString()+"*"+mExRate+"="+bigDecimalSettleAmount.toString());
                    bigDecimalMultiply = bigDecimalMultiply.setScale(2,BigDecimal.ROUND_HALF_UP);
                    bigDecimalSettleAmount = bigDecimalSettleAmount.setScale(2,BigDecimal.ROUND_HALF_UP);
                    multiply = bigDecimalMultiply.doubleValue();
                    SettleAmount = bigDecimalSettleAmount.doubleValue();
//                    Log.e("bb",bigDecimalMultiply.toString());

                    //获取货币数值格式
                    NumberFormat currency = NumberFormat.getCurrencyInstance();
                    currency.setMinimumFractionDigits(2);//设置数的小数部分所允许的最小位数(如果不足后面补0)
                    currency.setMaximumFractionDigits(2);//设置数的小数部分所允许的最大位数(如果超过会四舍五入)
                    aRebateAccount = currency.format(multiply);//￥12,343,171.60
                    double rebateAccount = account * rebates;

                    if (rebateAccount < 0) {
                        etAccountRebate.setText(" ");
                        tv_exchange_mExRate.setText("");
                    } else {
                        etAccountRebate.setText(multiply + " ");
                        tv_exchange_mExRate.setText(new DecimalFormat("0.00").format((Double.valueOf(multiply))*(Double.valueOf(tv_exchange_rate.getText().toString()))));
                    }
                }
            }
        });
    }

    private void initViews() {
        mQueue = Volley.newRequestQueue(getActivity());
        btnPay = (Button) getView().findViewById(R.id.btn_pay);
        tvBalance = (TextView) getView().findViewById(R.id.tv_balance);
        tvBalanceLayout=(LinearLayout)getView().findViewById(R.id.tv_balance_layout);
        etAccountAmount = (EditText) getView().findViewById(R.id.et_accountamount);
        tvRebate=(TextView)getView().findViewById(R.id.tv_rebate);
        tvPayS=(TextView)getView().findViewById(R.id.id_tv_payselect);
        etAccountRebate=(EditText)getView().findViewById(R.id.et_account_rebate);
        accountLayout=(LinearLayout)getView().findViewById(R.id.layout_account_rebate);
        rebateLayout=(LinearLayout)getView().findViewById(R.id.layout_rebate);
        payTypeLayout=(LinearLayout)getView().findViewById(R.id.layout_pay_type);
        currency_type= (TextView) getView().findViewById(R.id.currency_type);
        view0=(View)getView().findViewById(R.id.view_0);
        view1=(View)getView().findViewById(R.id.view_1);
        view2=(View)getView().findViewById(R.id.view_2);
        view3 = (View) getView().findViewById(R.id.view_3);
        view4 = (View) getView().findViewById(R.id.view_4);
        mDatalist = new ArrayList<>();
        pay_mtype = (TextView) getView().findViewById(R.id.pay_mtype);
        pay_type = (TextView) getView().findViewById(R.id.pay_type);
        tv_exchange_rate = (TextView) getView().findViewById(R.id.tv_exchange_rate);
        tv_amount_mExRate = (TextView) getView().findViewById(R.id.tv_amount_mExRate);
        tv_exchange_mExRate = (TextView) getView().findViewById(R.id.tv_exchange_mExRate);
        layout_exchange_mExRate = (LinearLayout) getView().findViewById(R.id.layout_exchange_mExRate);
        layout_exchange_rate = (LinearLayout) getView().findViewById(R.id.layout_exchange_rate);

        currencyrebate = (TextView) getView().findViewById(R.id.tv_currency_rebate);
        currencyrebateLayout = (LinearLayout) getView().findViewById(R.id.layout_currency_rebate);
        icon_vip = (TextView) getView().findViewById(R.id.icon_vip);
        Typeface iconfont = Typeface.createFromAsset(getActivity().getAssets(), "iconfont.ttf");
        icon_vip.setTypeface(iconfont);
    }


    /**
     * 获取余额
     */

    private void queryBalance() {
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), getActivity());
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.QueryBalanceHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取用户余额成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                   if (code.equals("200")) {//成功
                        JSONObject data = res.getJSONObject("data");
                        mAmount = data.getString("amount");
                       String currencyCode = data.getString("currencyCode");
                       String currency = data.getString("currency");
                    } else {//失败
                        TipUtil.showToast(message, getActivity(), 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), getActivity(), 1);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network),getActivity(), 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getActivity(). getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }
    @Override
    public void onResume() {
        super.onResume();
            queryBalance();
    }
    private void BuyPay(final String rebate){
        SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        String isCashPwdSet = mainSharedPreferences.getString("isCashPwdSet", "");

        if (isCashPwdSet.equals("1")) {
            String accountAmount = etAccountAmount.getText().toString();
            if (accountAmount.equals("") || accountAmount.equals("0")) {
                TipUtil.showToast(getResources().getString(R.string.error_please_input_amount), getActivity(), 1);
            } else if (SrcUtil.toAcoument(accountAmount)) {
                TipUtil.showToast(getResources().getString(R.string.error_amount_greater_million), getActivity(), 1);
            } else {
                switch (toPayType) {
//
                    case "0"://余额支付
                        paytoAcoument(rebate,bigDecimalMultiply.toString() , accountAmount, mAmount, "3",bigDecimalSettleAmount.toString());
                        break;
                    case "1"://快捷支付
                        paytoAcoument(rebate,bigDecimalMultiply.toString() , accountAmount, mAmount, "1",bigDecimalSettleAmount.toString());
                        break;
                    case "2"://银行卡支付
                        paytoBankCard(rebate, bigDecimalMultiply.toString(), accountAmount, cardNo, payType);
                        break;
                    case "3"://其它银行卡支付
                        paytoBankCard(rebate, bigDecimalMultiply.toString(), accountAmount, cardNo, payType);
                        break;
                    case "6"://paypal支付
                        paytoAcoument(rebate,bigDecimalMultiply.toString() , accountAmount, mAmount, "6",bigDecimalSettleAmount.toString());
                        break;
                    default:
//                                TipUtil.showToast("粗错啦！", getActivity(), 1);
                }
//                        etAccountAmount.setText("");
            }
        } else {
//                    跳转设置支付密码界面
            //询问是否取消
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(getResources().getString(R.string.text_prompt));
            builder.setMessage(getResources().getString(R.string.text_hint_notset_password));
            builder.setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), Setting_pwdPayActivity.class);
                    startActivity(intent);
                }
            });
            builder.setNegativeButton(getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.setCancelable(false);
            builder.create().show();

        }
    }

    private void paytoBankCard(String discount,String discountAmount,String orderAmount,String BankCard,String payType){
//        Log.e("pay","merchantId"+merchantId+"discount"+discount+"discountAmount"+discountAmount+"orderAmount"+orderAmount+"BankCard"+BankCard);
        payBankCard(merchantId, discount, discountAmount, orderAmount, BankCard);

//        etAccountAmount.setText("");
    }
    private void paytoAcoument(String discount,String discountAmount,String orderAmount,String mBlance,String payType,String settleAmount){
//        Log.e("paytoAcoument", discount + "&" + discountAmount + "&" + orderAmount + "&" + mBlance);

        if (payType.equals("1")){
            //实例化SelectPicPopupWindow
            menuWindow = new SelectPicPopupWindow(getActivity(),merchantId,discount,discountAmount,orderAmount,mBlance,payType,cardNo,settleAmount);
            //显示窗口
            //设置layout在PopupWindow中显示的位置
            menuWindow.showAtLocation(getActivity().findViewById(R.id.paymacth), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
            menuWindow.setPayPwdWindowListItemClickListener(new SelectPicPopupWindow.PayPwdWindowListItemClickListener() {
                @Override
                public void onPassWord(String pwd) {

                }

                @Override
                public boolean onSuccess(boolean message) {
                    if (message){
                        mContext.startActivity(new Intent(mContext, ChatActivity.class).putExtra("userId",aMerchant.getUserId()));
                    }
                    return message;
                }
            });
        } else if (payType.equals("0")){
            double balance = Double.parseDouble(mBlance);
            double account = Double.parseDouble(orderAmount);
            if (balance == 0 || account > balance) {
                TipUtil.showToast(getResources().getString(R.string.error_balance_not_enough), getActivity(), 1);
            } else {
                //实例化SelectPicPopupWindow
                menuWindow = new SelectPicPopupWindow(getActivity(),merchantId,discount,discountAmount,orderAmount,mBlance,payType,cardNo,settleAmount);
                //显示窗口
                //设置layout在PopupWindow中显示的位置
                menuWindow.showAtLocation(getActivity().findViewById(R.id.paymacth), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
//
                menuWindow.setPayPwdWindowListItemClickListener(new SelectPicPopupWindow.PayPwdWindowListItemClickListener() {
                    @Override
                    public void onPassWord(String pwd) {

                    }

                    @Override
                    public boolean onSuccess(boolean message) {
                        if (message){
                            mContext.startActivity(new Intent(mContext, ChatActivity.class).putExtra("userId",aMerchant.getUserId()));
                        }
                        return message;
                    }
                });

            }

        }else if (payType.equals("6")){
            pay(merchantId,discount,discountAmount,orderAmount,payType,settleAmount);

        }


    }
    /**
     * paypal支付
     */
    private void pay(final String MerchantId, final String discount, final String discountAmount, final String orderAmount,final String type,final String settleAmount) {
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME,getActivity().getResources().getString(R.string.error_please_waitting), getActivity());
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.ApplyConsume, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("确认支付接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        JSONObject data = res.getJSONObject("data");
                        String inputCharset = data.getString("inputCharset");
                        String language = data.getString("language");
                        String orderAmount = data.getString("orderAmount");
                        String payPalUrl = data.getString("payPalUrl");
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), PayPalWindowActivity.class);
                        intent.putExtra("payPalUrl",payPalUrl);
                        startActivity(intent);
                    } else {//失败
                        TipUtil.showToast(message, mContext, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(mContext.getResources().getString(R.string.error_service), mContext, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(mContext.getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId","");
                map.put("loginId", userId);
                map.put("payerId",userId);
                map.put("recieverId",MerchantId);
                map.put("orderAmount",orderAmount);
                map.put("discount",discount);
                map.put("discountAmount",discountAmount+"");
                map.put("accountAmount","0");
                map.put("cardAmount",discountAmount);
                map.put("fee","0");
                map.put("payMethod", type);
//                0：普通  1：商品订单
                map.put("orderType","0");
                map.put("settleAmount",settleAmount);//汇率计算后金额
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        //stringRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(stringRequest);
    }


    private void payBankCard(final String MerchantId, final String discount, final String discountAmount, final String orderAmount, final String BankCard) {

//        Log.e("pay",orderAmount+"&"+MerchantId+"&"+discount+"&"+discountAmount);
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, mContext.getResources().getString(R.string.error_please_waitting), getActivity());
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.ApplyConsume, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("确认支付接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
//                        TipUtil.showToast("支付成功", getActivity(), 1);
                        JSONObject Data = res.getJSONObject("data");
//                        Log.e("text", Data.getString("issuerId") + "&" + Data.getString("tradeNature"));
                        String issuerId=Data.getString("issuerId");
                        String tradeNature=Data.getString("tradeNature");
                        String signType=Data.getString("signType");
                        String orderCurrency=Data.getString("orderCurrency");
                        String version=Data.getString("version");
                        String cardNo=Data.getString("cardNo");
                        String receiveUrl=Data.getString("receiveUrl");
                        String inputCharset=Data.getString("inputCharset");
                        setOrderNo(Data.getString("orderNo"));
                        orderNo=Data.getString("orderNo");
                        String ext1=Data.getString("ext1");
                        String orderAmount=Data.getString("orderAmount");
                        String signMsg=Data.getString("signMsg");
                        String payType=Data.getString("payType");
                        String merchantId=Data.getString("merchantId");
                        String language=Data.getString("language");
                        String orderDatetime=Data.getString("orderDatetime");
                        String productName=Data.getString("productName");
                        if (!(issuerId==null||issuerId.equals(""))){
                            if (!(tradeNature==null||tradeNature.equals(""))){
                                JSONObject paaParams = new JSONObject();
                                try {
                                    paaParams.put("inputCharset", inputCharset);
                                    paaParams.put("receiveUrl", receiveUrl);
                                    paaParams.put("version", version);
                                    paaParams.put("signType", signType);
                                    paaParams.put("merchantId", merchantId);
                                    paaParams.put("orderNo", orderNo);
                                    paaParams.put("orderAmount", orderAmount);
                                    paaParams.put("orderCurrency", orderCurrency);
                                    paaParams.put("orderDatetime", orderDatetime);
                                    paaParams.put("productName",productName);
//                                    paaParams.put("ext1", ext1);
                                    paaParams.put("payType", payType);
//                        paaParams.put("issuerId", "visa");
//                        paaParams.put("tradeNature", "GOODS");
                                    paaParams.put("language",language);
                                    if (!(BankCard.equals("BankCardNo"))){
                                        paaParams.put("cardNo",BankCard);
                                    }else {
                                        paaParams.put("cardNo",cardNo);
                                    }
                                    paaParams.put("signMsg",signMsg);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                APPayAssistEx.startPay(getActivity(), paaParams.toString(), Constant.PAYKEY);
                            }
                        }else {
                            APPayAssistEx.startPay(getActivity(), Data.toString(), Constant.PAYKEY);

                        }

                    } else {//失败
                        TipUtil.showToast(message, getActivity(), 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(mContext.getResources().getString(R.string.error_service), getActivity(), 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(mContext.getResources().getString(R.string.error_network), getActivity(), 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =getActivity(). getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId","");
                map.put("loginId", userId);
                map.put("payerId",userId);
                map.put("recieverId",MerchantId);
                map.put("orderAmount",orderAmount);
                map.put("discount",discount);
                map.put("discountAmount",discountAmount);
                map.put("accountAmount","0");
                map.put("cardAmount",discountAmount);
                map.put("fee","0");
                map.put("payMethod","2");
                //                0：普通  1：商品订单
                map.put("orderType","0");
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        //stringRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        mQueue.add(stringRequest);
    }

    private void PayPal(final String shopId) {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), getActivity());
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.PayPal, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("407")){
                        TipUtil.showAppayRes(getActivity());
                    }
                    if (code.equals("200")) {//成功
                        JSONObject aData = res.getJSONObject("data");
                        Merchant merchant = new Merchant();
                        merchant.setUserId(aData.getString("userId"));
                        merchant.setShopId(aData.getString("shopId"));
                        merchant.setShopName(aData.getString("shopName"));
//                            Log.e("name",aData.getString("shopName"));
                        merchant.setLogo(aData.getString("logo"));
                        merchant.setDiscount(aData.getString("discount"));
                        merchant.setAddress(aData.getString("address"));
                        merchant.setTelephone(aData.getString("telephone"));
                        merchant.setTelephoneOne(aData.getString("telephoneOne"));
                        merchant.setMobile(aData.getString("mobile"));
                        merchant.setDesc(aData.getString("desc"));
                        merchant.setCity(aData.getString("city"));
                        merchant.setImage(aData.getString("image"));
                        merchant.setUserId(aData.getString("userId"));
                        merchant.setVipdiscount(aData.getString("vipDiscount"));
                        merchant.setLastTopic(aData.getString("lastTopic"));
                        merchant.setNewGoods(aData.getString("newGoods"));
                        merchant.setLevel(aData.getInt("level"));
                        merchant.setDetailsUrl(aData.getString("detailsUrl"));
                        merchant.setNationalFlag(aData.getString("nationalFlag"));
                        merchant.setCurrencyCode(aData.getString("currencyCode"));
                        merchant.setCurrency(aData.getString("currency"));
                        merchant.setExRate(aData.getString("exRate"));
                        if (aData.getString("isVip")==null|"".equals(aData.getString("isVip"))){

                        }else {
                            isVIP=aData.getString("isVip");
                        }
                        aMerchant = merchant;
                        merchantId=aMerchant.getShopId();
                        countAmount(aMerchant);

                    } else {//失败
                        TipUtil.showToast(message, getActivity(), 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service),getActivity(), 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), getActivity(), 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("loginId", userId);
                map.put("shopId",shopId);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =getActivity(). getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

    public void countAmount(Merchant Merchant){
        String discount = Merchant.getDiscount();
        String vipDiscount = Merchant.getVipdiscount();
        String vipDiscountDeduct = Merchant.getVipDiscountDeduct();
        String discountDeduct = Merchant.getDiscountDeduct();
        String exRate = Merchant.getExRate();
//        Log.e("exRate",exRate);
        isVIP = Merchant.getIsVip();
        tvBalance.setText(mAmount);
        merchantId = Merchant.getShopId();
        pay_type.setText(Merchant.getCurrencyCode());

        pay_mtype.setText(Merchant.getCurrencyCode());
        tv_exchange_rate.setText(exRate);
        currency_type.setText(PreferenceManager.getInstance().getCountryCode());
        String languageCode = PreferenceManager.getInstance().getLanguageCode();
        if ("1".equals(exRate)){
            layout_exchange_rate.setVisibility(View.GONE);
            view3.setVisibility(View.GONE);
            layout_exchange_mExRate.setVisibility(View.GONE);
            view4.setVisibility(View.GONE);
        }else{
            tv_amount_mExRate.setText(PreferenceManager.getInstance().getCountryCode()+"   "+getActivity().getResources().getString(R.string.text_recharge_amount));
        }
        if ("zh-CN".equals(languageCode)) {//中文折扣显示
            if (discount.equals("10")){
                rebateLayout.setVisibility(View.GONE);
            }
            if ("1".equals(isVIP)){
                tvRebate.setText(vipDiscount+getResources().getString(R.string.text_discounted));
                initEvents(vipDiscount,exRate);
            }else {
                icon_vip.setVisibility(View.GONE);
                tvRebate.setText(discount+getResources().getString(R.string.text_discounted));
                initEvents(discount,exRate);
            }

        }else {
            if (discountDeduct.equals("0")){
                rebateLayout.setVisibility(View.GONE);
            }
            if ("1".equals(isVIP)){
                tvRebate.setText(vipDiscountDeduct+getResources().getString(R.string.text_discountDeduct));
                initEvents(vipDiscount,exRate);
            }else {
                icon_vip.setVisibility(View.GONE);
                tvRebate.setText(discountDeduct+getResources().getString(R.string.text_discountDeduct));
                initEvents(discount,exRate);
            }
        }


    }

    /**
     * 获取支付方式
     */
    private void GetPayType(final String Type,final String MerchantId,final String Amount) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.getPayMethod, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {

                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    JSONObject aData=res.getJSONObject("data");

//                    tv_Balance.setText(balance);
                    if (code.equals("200")) {//成功
                        String balance = aData.getString("balance");
                        String currencyCode = aData.getString("currencyCode");
                        String payMethod = aData.getString("payMethod");
                        String currency = aData.getString("currency");
                        mCardList.clear();
//                        mMTList.clear();
                        JSONArray cardList = aData.getJSONArray("cardList");
//                        JSONArray MTList = aData.getJSONArray("MTList");
                        for (int i = 0; i < cardList.length(); i++) {
                            JSONObject item = (JSONObject) cardList.get(i);
                            BankCard bankCard = new BankCard();
                            bankCard.setPhone(item.getString("phone"));
                            bankCard.setCardName(item.getString("cardName"));
                            bankCard.setBankCardNo(item.getString("bankCardNo"));
                            bankCard.setAvailable(item.getString("available"));
                            bankCard.setLimit(item.getString("limit"));
                            bankCard.setBankCode(item.getString("bankCode"));
                            bankCard.setCardType(item.getString("accountType"));
                            bankCard.setRemarks(item.getString("remarks"));
                            bankCard.setIsActive(item.getString("isActive"));
                            mCardList.add(bankCard);
                        }
//                        for (int i = 0; i < MTList.length(); i++) {
//                            JSONObject item = (JSONObject) MTList.get(i);
//                            BankCard bankCard = new BankCard();
//                            bankCard.setPhone(item.getString("phone"));
//                            bankCard.setCardName(item.getString("cardName"));
//                            bankCard.setBankCardNo(item.getString("bankCardNo"));
//                            bankCard.setBankCode(item.getString("bankCode"));
//                            bankCard.setCardType(item.getString("accountType"));
//                            bankCard.setRemarks(item.getString("remarks"));
//                            bankCard.setAvailable(item.getString("available"));
//                            bankCard.setLimit(item.getString("limit"));
//                            mMTList.add(bankCard);
//                        }
                        payWindow = new PayPopupWindow(getActivity(),"0","1",mCardList);
                        payWindow.setAmount(etAccountAmount.getText().toString());
                        payWindow.setmCardList(mCardList);
//                        payWindow.setmMTList(mMTList);
                        payWindow.setBalance(balance);
                        payWindow.setCurrency(currency);
                        payWindow.setCurrencyCode(currencyCode);
                        payWindow.setPayMethod(payMethod);
                        payWindow.setShop(aMerchant);
                        payWindow.setPayWindowListItemClickListener(new PayPopupWindow.PayWindowListItemClickListener() {
                            @Override
                            public void onItemClick(BankCard message) {

                                String CardName = message.getCardName();
                                tvPayS.setText(CardName);
                                if (getActivity().getResources().getString(R.string.text_blance_pay).equals(CardName)){
                                    tvBalance.setText(message.getBankCardNo());
                                }else if (getActivity().getResources().getString(R.string.text_phone_pay).equals(CardName)){

                                }else {
                                    tvBalance.setText("");
                                    cardNo = message.getBankCardNo();
                                }
                                BuyPay(MyRebate);
                            }

                            @Override
                            public void onPayTypeClick(String Type) {
                                toPayType = Type;

                            }
                        });
                        //显示窗口
                        //设置layout在PopupWindow中显示的位置
                        payWindow.showAtLocation(getActivity().findViewById(R.id.paymacth), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);

                    } else {//失败
                        TipUtil.showToast(message, mContext, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(mContext.getResources().getString(R.string.error_service),mContext, 1);
                }

                TipUtil.closeProgressDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(mContext.getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("shopId",MerchantId);
                map.put("amount",Amount);
                map.put("type",Type);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);


    }


}
